package cz.swosh.stomp.web;

import java.io.IOException;


import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.crypto.hash.*;

/**
 * Uses JSecurity to authenticate a user
 * If user can be authenticated successfully
 * forwards user to /secure/index.jsp
 * 
 * If user cannot be authenticated then forwards
 * user to the /login.jsp which will display
 * an error message
 *
 */
public class Login extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

    static final long serialVersionUID = 1L;
    private static final String salt = "maminkamojemila";
    private static final String urlFail = "/stompear-web/index.jsp?page=login";
    private static final String urlUzivatel = "/stompear-web/sprava/index.jsp?page=sprava";


    /* (non-Java-doc)
     * @see javax.servlet.http.HttpServlet#HttpServlet()
     */
    public Login() {
        super();
    }

    /* (non-Java-doc)
     * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request, response);
    }

    /* (non-Java-doc)
     * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/xhtml+xml;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        //see /login.jsp for these form fields
        String username = request.getParameter("email").trim();
        String password = request.getParameter("heslo");
        Hash hashPass = new Sha512Hash(password, salt);
        String hashHex = hashPass.toHex();
        //create a UsernamePasswordToken using the
        //username and password provided by the user
        //See:  http://jsecurity.org/api/org/jsecurity/authc/UsernamePasswordToken.html
        UsernamePasswordToken token =
                new UsernamePasswordToken(username, hashHex);

        try {

            //get the user (aka subject) associated with
            //this request.

            Subject subject = SecurityUtils.getSubject();

            //The use of JSecurityFilter specified in web.xml
            //caused JSecurity to create the DefaultWebSecurityManager object
            //see: http://jsecurity.org/api/org/jsecurity/web/DefaultWebSecurityManager.html
            //This security manager is the default for web-based applications
            //The SecurityUtils was provided that security manager automatically
            //The configuration specified in web.xml caused
            //a JdbcRealm object to be provided to the SecurityManager
            //so when the login method is called that JdbcRealm
            //object will be used
            //This application uses all the other defaults
            //For example the default authentication query string is
            //"select password from users where username = ?"
            //since the database this application uses (securityDB)
            //has a users table and that table has a column named username
            //and a column named password, the default authentication query
            //string will work
            //see http://jsecurity.org/api/constant-values.html#org.jsecurity.realm.jdbc.JdbcRealm.DEFAULT_AUTHENTICATION_QUERY
            //The call to login will cause the following to occur
            //JSecurity will query the database for a password associated with the
            //provided username (which is stored in token).  If a password is found
            //and matches the password
            //provided by the user (also stored in the token), a new Subject will be created that is
            //authenticated.  This subject will be bound to the session for the
            //user who made this request
            //see:  http://jsecurity.org/api/org/jsecurity/authc/Authenticator.html#authenticate(org.jsecurity.authc.AuthenticationToken)
            //for a list of potential Exceptions that might be generated if
            //authentication fails (e.g. incorrect password, no username found)

            subject.login(token);

            if (subject.hasRole("reg")) {
                //clear the information stored in the token
                //see: http://jsecurity.org/api/org/jsecurity/authc/UsernamePasswordToken.html#clear()

                token.clear();

                response.sendRedirect(urlUzivatel);
                return;

            } else {
                subject.logout();
                request.setAttribute("chyba", "Uživatel není aktivován.");
            }

        } catch (UnknownAccountException ex) {
            //username provided was not found
            ex.printStackTrace();
            request.setAttribute("chyba", "Uživatel nebyl nalezen.");

        } catch (IncorrectCredentialsException ex) {
            //password provided did not match password found in database
            //for the username provided
            ex.printStackTrace();
            request.setAttribute("chyba", "Heslo není správně zadáno.");
        } catch (Exception ex) {

            ex.printStackTrace();

            request.setAttribute("chyba", "Přihlášení se nezdařilo. Chyba není u uživatele.");

        }


        // forward the request and response to the view
           response.setHeader("test", "test");

        RequestDispatcher dis = request.getRequestDispatcher(urlFail);
        dis.forward(request, response);


    }

}
